package com.chinasoftinc.facommon.control.conversation;

import ohos.app.Context;
import ohos.interwork.utils.PacMapEx;
import ohos.utils.zson.ZSONObject;

import ohos.agp.utils.TextTool;

import com.huawei.ailife.service.kit.AiLifeServiceHelper;
import com.huawei.ailife.service.kit.callback.DataCallback;
import com.huawei.ailife.service.kit.constants.ApiParameter;
import com.huawei.ailife.service.kit.manager.DeviceManager;
import com.huawei.ailife.service.kit.model.AiLifeServiceParamBuilder;
import com.huawei.ailife.service.kit.model.CommandParam;
import com.huawei.ailife.service.kit.model.HiLinkDevice;

import com.chinasoftinc.facommon.DeviceControlConstants;
import com.chinasoftinc.facommon.FAConfigMgr;
import com.chinasoftinc.facommon.utils.LogUtil;

import java.util.Objects;

/**
 * 设备控制辅助工具类
 *
 * @since 2021-08-11
 */
public class HiLinkDeviceHelper {
    private static final String TAG = "HiLinkDeviceHelper";
    private String deviceId;
    private final DeviceManager deviceManager;
    private HiLinkDataCallback hiLinkDataCallback;
    private Conversation conversation;
    private Context context;

    /**
     * 构造方法
     *
     * @param deviceId 设备deviceId
     */
    public HiLinkDeviceHelper(Context context, String deviceId) {
        this.context = context;
        this.deviceId = deviceId;
        AiLifeServiceParamBuilder builder = new AiLifeServiceParamBuilder();
        builder.addScope(ApiParameter.Scope.FEATURE_REQUEST_CLOUD)
            .addScope(ApiParameter.Scope.FEATURE_CLOUD_CONTROL);
        PacMapEx parameters = builder.createParameters();
        deviceManager = (DeviceManager) AiLifeServiceHelper.getService(AiLifeServiceHelper.DEVICE_MANAGER_SERVICE,
            parameters);
        Objects.requireNonNull(deviceManager);
    }

    /**
     * 设置数据回调
     *
     * @param hiLinkDataCallback 回调对象
     */
    public void setHiLinkDataCallback(HiLinkDataCallback hiLinkDataCallback) {
        this.hiLinkDataCallback = hiLinkDataCallback;
    }

    /**
     * 下发指令
     *
     * @param serviceId 要控制的设备服务的ID
     * @param param 控制的参数
     */
    public void sendCommand(String serviceId, String param) {
        LogUtil.info(TAG, "deviceId: " + deviceId + ", serviceId: " + serviceId + ", param: " + param);
        CommandParam.Builder builder = new CommandParam.Builder()
            .mode(FAConfigMgr.get().isBleMode() ? ApiParameter.CommandMode.MODE_BLE : ApiParameter.CommandMode.MODE_AUTO)
            .type(ApiParameter.CommandType.SERVICE_ID)
            .serviceId(serviceId);
        if (!TextTool.isNullOrEmpty(param)) {
            ZSONObject zsonObject = ZSONObject.stringToZSON(param);
            for (String key : zsonObject.keySet()) {
                builder.addCharastic(key, zsonObject.get(key));
            }
        }
        CommandParam commandParam = builder.build();
        LogUtil.info(TAG, "commandParam = " + ZSONObject.toZSONString(commandParam));
        conversation.sendCommand(commandParam);
    }

    public void createConversation() {
        conversation = FAConfigMgr.get().isBleMode() ? new BleConversation(context) : new WifiConversation(deviceManager, deviceId);
        conversation.setHiLinkDataCallback(hiLinkDataCallback);
        conversation.init();
    }

    /**
     * 获取设备信息
     */
    public void getHiLinkDevice() {
        LogUtil.info(TAG, "getHiLinkDevice deviceId: " + deviceId);
        LogUtil.info(TAG, "getHiLinkDevice deviceManager: " + deviceManager);
        deviceManager.getHiLinkDevice(ApiParameter.Source.FROM_CLOUD, deviceId,
            new DataCallback<HiLinkDevice>() {
                @Override
                public void onSuccess(HiLinkDevice hiLinkDevice) {
                    LogUtil.info(TAG, "getHiLinkDevice onSuccess = " + ZSONObject.toZSONString(hiLinkDevice));
                    Objects.requireNonNull(hiLinkDataCallback).onSuccess(DeviceControlConstants.GET_DEVICE,
                        ZSONObject.toZSONString(hiLinkDevice));
                    conversation.withHiLinkDevice(hiLinkDevice);
                    LogUtil.info(TAG, "HiLinkDevice start connect device");
                    conversation.connect();
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    LogUtil.info(TAG, "getHiLinkDevice onFailure: errorCode = " + errorCode + ", msg = " + msg);
                    hiLinkDataCallback.onFail(DeviceControlConstants.GET_DEVICE, errorCode, msg);
                }
            });
    }

    /**
     * 与设备蓝牙断开连接
     */
    public void disConnect() {
        LogUtil.info(TAG, "disconnect deviceId: " + deviceId);
        if (conversation != null) {
            conversation.disconnect();
        }
    }

    public String getDeviceId() {
        return this.deviceId;
    }

    /**
     * 配置设备ID
     *
     * @param newDeviceId 新的设备ID
     */
    public void setDeviceId(String newDeviceId) {
        if (conversation != null) {
            conversation.onDeviceIdChange();
        }
        if (this.deviceId == null) {
            this.deviceId = newDeviceId;
            return;
        }
        if (this.deviceId.equals(newDeviceId)) {
            return;
        } else {
            LogUtil.info(TAG, "setDeviceId after : " + newDeviceId);
            this.deviceId = newDeviceId;
        }
    }
}
